package com.fingard.dsp.bank.directbank.abc02;

import com.fingard.client.DspClient;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IBalanceCheck;
import com.fingard.dsp.bank.helpers.FileType;
import com.fingard.dsp.bank.reqrespobj.balancecheck.ReqBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.RetAtsBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.detail.RetAtsBalCheckDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.TcpReceiver;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

public class ABC02BalanceCheck extends ABC02Base implements IBalanceCheck {
    @Override
    public RetAtsBalCheckQry d_7508_BalCheck(ReqBalCheckQry p_req7508) throws Exception {
        RetAtsBalCheckQry retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
        retAts.writeStart();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "DQLT05";
            bankHeader.ReqSeqNo = p_req7508.reqHeader.transSeqID;
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("Corp");
            xmlWriter.writeElementString("StartDate", p_req7508.yearMonth);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpFileFlag = tmpBkReader.getFirstText("/ap/FileFlag");
                    String tmpRespCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    String tmpRespSource = tmpBkReader.getFirstText("/ap/RespSource");

                    if (tmpRespSource != null && "0".equals(tmpRespSource) && StringHelper.hasAnyChar(tmpRespCode)) {
                        if ("1".equals(tmpFileFlag)) {
                            String tmpBatchFileName = tmpBkReader.getFirstText("/ap/Cmp/BatchFileName");
                            String tmpFilePath = "";
                            String tmpQryPayFolder = bankFront.bkQryPayFolder;
                            if (p_req7508.reqHeader.transType.equals("7508")) {
                                tmpFilePath = StringHelper.trimEnd(tmpQryPayFolder, File.separator) + File.separator + tmpBatchFileName;
                            }
                            this.WriteBankLogLn("读取前置数据文件：" + tmpFilePath);
                            String tmpResultData = "";
                            if ("dspfileserver".equals(this.bankFront.getAccessBkFileModeLowerCase())) {
                                WriteBankLogLn("accessBkFileMode：" + bankFront.accessBkFileMode);
                                DspClient dspClient = new DspClient(bankFront.dspFileServer);
                                dspClient.charsetName = getCharset();
                                TcpReceiver tcpRec = dspClient.getFile(FileType.bankFile, tmpFilePath);
                                if (tcpRec.isCompleted) {
                                    if (tcpRec.isRtnBinaryFile) {
                                        tmpResultData = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                    } else {
                                        String errMsg = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                        WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + errMsg);
                                    }
                                } else {
                                    this.WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + tcpRec.getConnMsg());
                                }
                            } else if ("ftp".equals(this.bankFront.getAccessBkFileModeLowerCase())) {
                                FtpSet ftpSet = bankFront.getFtpSet("balCheck");
                                String downFilePath = StringHelper.trimEndFileSp(ftpSet.downDir) + "/" + tmpBatchFileName;
                                FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                                ftpPtClient.connect();
                                FtpReceiver ftpReceiver = ftpPtClient.downloadFile(downFilePath, tmpFilePath);
                                if (ftpReceiver.isCompleted) {
                                    WriteBankLogLn("成功下载结果文件:" + tmpBatchFileName + "至" + tmpFilePath);
                                } else {
                                    WriteBankLogLn(tmpBatchFileName + "结果文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                                    retAts.writeRespInfo("-1");
                                    retAts.writeRespInfo(tmpBatchFileName + "结果文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                                    return retAts;
                                }
                                tmpResultData = FileHelper.readFileText(tmpFilePath, getCharset());
                                WriteBankLogLn("结果文件内容为:" + tmpResultData);

                            } else {
                                tmpResultData = FileHelper.readFileText(tmpFilePath, getCharset());
                            }
                            WriteBankLogLn("银行查询文件返回内容为：" + tmpResultData);
                            StringBuilder tmpSbLog = new StringBuilder();
                            int fieldNum = Integer.valueOf(tmpBkReader.getFirstText("/ap/Cme/FieldNum"));
                            ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpResultData, "|", fieldNum, -1, tmpSbLog);
                            if (tmpSbLog.length() == 0) {
                                retAts.writeRespCode("0");
                                WriteBankLogLn("返回的记录条数：" + tmpArrayList.size());

                                for (int i = 0; i < tmpArrayList.size(); i++) {

                                    /**
                                     * 文件内容格式：
                                     *    0       1       2      3                   4                   5             6      7      8
                                     * 账单日期|账单编号|账单号|所属机构号（网点）|所属机构号（省行）|所属机构号（二级分行）|客户号|单位名称|单位地址|
                                     * [202005, 200541001412000689, 410014000533, 410014, 41, 419999, 6681500001337159, 华润水泥投资有限公司,深圳市罗湖区桂园街道老围社区罗湖区深南东路5016号蔡屋围京基一百大厦A座3001,
                                     *
                                     *   9      10     11      12         13         14     15    16         17
                                     * 收件人|联系人|固定电话|移动电话|对账单对账状态|对账结果|对账员|复核员|生成对账结果标志|
                                     * 华润水泥投资有限公司,李俊颖, 755 -82691722, 13570890818, A, , , , ]
                                     */
                                    String[] tmpEachArr = tmpArrayList.get(i);
                                    WriteBankLogLn("返回的记录长度：" + tmpEachArr.length);
                                    WriteBankLogLn("返回的记录内容：" + Arrays.toString(tmpEachArr));
                                    RetAtsBalCheckDetail tmpRetDetail = new RetAtsBalCheckDetail();
                                    tmpRetDetail.yearMonth = tmpEachArr[0];
                                    String balDate = tmpEachArr[0];
                                    if (balDate.length() == 8) {
                                        tmpRetDetail.balDate = balDate.substring(0, 4) + "-" + balDate.substring(4, 6) + "-" + balDate.substring(6, 8);
                                    } else {
                                        tmpRetDetail.balDate = balDate;
                                    }
                                    tmpRetDetail.fixDate = tmpRetDetail.balDate;
                                    tmpRetDetail.statementNumber = tmpEachArr[1];
                                    tmpRetDetail.prcBrn = tmpEachArr[3];
                                    tmpRetDetail.actBrn = tmpEachArr[4];
                                    tmpRetDetail.lgrBrn = tmpEachArr[5];
                                    tmpRetDetail.cltNbr = tmpEachArr[6];
                                    tmpRetDetail.telNbr = tmpEachArr[11];
                                    tmpRetDetail.mobile = tmpEachArr[12];
                                    String dzFlag = tmpEachArr[14];
                                    String atsFlag = "";
                                    if (tmpEachArr[13].equals("A")) {
                                        atsFlag = "1";
                                    } else {
                                        if ("A".equals(dzFlag)) {
                                            atsFlag = "2";
                                        } else if ("B".equals(dzFlag) || "C".equals(dzFlag)) {
                                            atsFlag = "3";
                                        }
                                    }
                                    tmpRetDetail.dzFlag = atsFlag;
                                    tmpRetDetail.operator = tmpEachArr[15];
                                    if (StringHelper.hasAnyChar(tmpRetDetail.statementNumber)) {
                                        d_7508_DQLT07(p_req7508, tmpRetDetail);
                                    } else {
                                        break;
                                    }
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                retAts.writeRespCode("0");
                                retAts.writeRespInfo(tmpSbLog.toString());
                            }
                        } else if ("0".equals(tmpFileFlag)) {
                            retAts.writeRespCode("0");
                            retAts.writeRespInfo("处理中");
                        } else {
                            retAts.writeRespCode("0");
                            if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                                retAts.writeRespInfo(tmpRetRxtInfo);
                            } else {
                                retAts.writeRespInfo(tmpRetInfo);
                            }
                        }
                    } else {
                        retAts.writeRespCode("0");
                        retAts.writeRespInfo(tmpRetInfo);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAtsBalCheckQry d_7508_DQLT07(ReqBalCheckQry p_req7508, RetAtsBalCheckDetail tmpRetDetail) throws Exception {
        RetAtsBalCheckQry retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
        retAts.writeStart();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "DQLT07";
            bankHeader.ReqSeqNo = p_req7508.reqHeader.transSeqID;
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("TCAS");
            xmlWriter.writeElementString("BillSerial", tmpRetDetail.statementNumber);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpFileFlag = tmpBkReader.getFirstText("/ap/FileFlag");
                    String tmpRespCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    String tmpRespSource = tmpBkReader.getFirstText("/ap/RespSource");

                    if (tmpRespSource != null && "0".equals(tmpRespSource) && StringHelper.hasAnyChar(tmpRespCode)) {
                        if ("1".equals(tmpFileFlag)) {
                            String tmpBatchFileName = tmpBkReader.getFirstText("/ap/Cmp/BatchFileName");
                            String tmpFilePath = "";
                            String tmpQryPayFolder = bankFront.bkQryPayFolder;
                            if (p_req7508.reqHeader.transType.equals("7508")) {
                                tmpFilePath = StringHelper.trimEnd(tmpQryPayFolder, File.separator) + File.separator + tmpBatchFileName;
                            }
                            this.WriteBankLogLn("读取前置数据文件：" + tmpFilePath);
                            String tmpResultData = "";
                            if ("dspfileserver".equals(this.bankFront.getAccessBkFileModeLowerCase())) {
                                WriteBankLogLn("accessBkFileMode：" + bankFront.accessBkFileMode);
                                DspClient dspClient = new DspClient(bankFront.dspFileServer);
                                dspClient.charsetName = getCharset();
                                TcpReceiver tcpRec = dspClient.getFile(FileType.bankFile, tmpFilePath);
                                if (tcpRec.isCompleted) {
                                    if (tcpRec.isRtnBinaryFile) {
                                        tmpResultData = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                    } else {
                                        String errMsg = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                        WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + errMsg);
                                    }
                                } else {
                                    this.WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + tcpRec.getConnMsg());
                                }
                            } else if ("ftp".equals(this.bankFront.getAccessBkFileModeLowerCase())) {
                                FtpSet ftpSet = bankFront.getFtpSet("balCheck");
                                String downFilePath = StringHelper.trimEndFileSp(ftpSet.downDir) + "/" + tmpBatchFileName;
                                FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                                ftpPtClient.connect();
                                FtpReceiver ftpReceiver = ftpPtClient.downloadFile(downFilePath, tmpFilePath);
                                if (ftpReceiver.isCompleted) {
                                    WriteBankLogLn("成功下载结果文件:" + tmpBatchFileName + "至" + tmpFilePath);
                                } else {
                                    WriteBankLogLn(tmpBatchFileName + "结果文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                                    retAts.writeRespInfo("-1");
                                    retAts.writeRespInfo(tmpBatchFileName + "结果文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                                    return retAts;
                                }
                                tmpResultData = FileHelper.readFileText(tmpFilePath, getCharset());
                                WriteBankLogLn("结果文件内容为:" + tmpResultData);

                            } else {
                                tmpResultData = FileHelper.readFileText(tmpFilePath, getCharset());
                            }
                            WriteBankLogLn("银行查询文件返回内容为：" + tmpResultData);
                            StringBuilder tmpSbLog = new StringBuilder();
                            int fieldNum = Integer.valueOf(tmpBkReader.getFirstText("/ap/Cme/FieldNum"));
                            ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpResultData, "|", fieldNum, -1, tmpSbLog);
                            if (tmpSbLog.length() == 0) {
                                retAts.writeRespCode("0");
                                WriteBankLogLn("返回的记录条数：" + tmpArrayList.size());

                                for (int i = 0; i < tmpArrayList.size(); i++) {

                                    /**
                                     * 文件内容格式：
                                     *     0     1   2    3     4     5      6
                                     * 省市代码|账号|币种|户名|账户类型|余额|结果标志|
                                     *
                                     * 账户类型:  0-结算账户 1-定期账户 2-通知账户 3-协议账户 4-保证金账户 5-贷款账户
                                     * 结果标志:  Y-余额相符 N-余额不符
                                     */
                                    String[] tmpEachArr = tmpArrayList.get(i);
                                    WriteBankLogLn("返回的记录长度：" + tmpEachArr.length);
                                    WriteBankLogLn("返回的记录内容：" + Arrays.toString(tmpEachArr));
                                    if(tmpEachArr.length < 7){
                                    	WriteBankLogLn("第"+(i+1)+"行数据拆分后的记录长度：" + tmpEachArr.length+"，小于7，不符合预期");
                                    	continue;
                                    }
                                    String actNum = p_req7508.actNum;
                                    
                                    if (actNum.length() >= 15){
                                    	actNum = actNum.substring(actNum.length() - 15);
                                    }
                                    String bkAct = tmpEachArr[1];
                                    if (bkAct.length() >= 15) {
                                    	bkAct = bkAct.substring(bkAct.length() - 15);
                                    }
                                    if (actNum.equals(bkAct)) {
                                        tmpRetDetail.actNum = p_req7508.actNum;
                                        tmpRetDetail.actCur = convertCurToATS(tmpEachArr[2]);
                                        tmpRetDetail.actName = tmpEachArr[3];
                                        //存款种类（1往来户,2贷款户,3定期户,4保证金户，5内部户，6个人贷款综合账户，9其他，34定期保证金户）
                                        if ("1".equals(tmpEachArr[4])) {
                                            tmpRetDetail.acctType = "3";
                                        } else if ("4".equals(tmpEachArr[4])) {
                                            tmpRetDetail.acctType = "4";
                                        } else if ("5".equals(tmpEachArr[4])) {
                                            tmpRetDetail.acctType = "2";
                                        } else {
                                            tmpRetDetail.acctType = "9";
                                        }
                                        tmpRetDetail.accNbr = tmpEachArr[5];
                                        if ("Y".equals(tmpEachArr[6])) {
                                            tmpRetDetail.dzFlag = "2";
                                        } else if ("N".equals(tmpEachArr[6])) {
                                            tmpRetDetail.dzFlag = "3";
                                        }
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                            } else {
                                retAts.writeRespCode("0");
                                retAts.writeRespInfo(tmpSbLog.toString());
                            }
                        } else if ("0".equals(tmpFileFlag)) {
                            retAts.writeRespCode("0");
                            retAts.writeRespInfo("处理中");
                        } else {
                            retAts.writeRespCode("0");
                            if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                                retAts.writeRespInfo(tmpRetRxtInfo);
                            } else {
                                retAts.writeRespInfo(tmpRetInfo);
                            }
                        }
                    } else {
                        retAts.writeRespCode("0");
                        retAts.writeRespInfo(tmpRetInfo);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }
}
